package com.ruoyi.business.service.impl;

import java.util.List;

import com.ruoyi.business.domain.Shop;
import com.ruoyi.business.mapper.ShopMapper;
import com.ruoyi.common.core.utils.DateUtils;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.ParsedAggregation;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.ParsedAvg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.ServiceEvaluateMapper;
import com.ruoyi.business.domain.ServiceEvaluate;
import com.ruoyi.business.service.IServiceEvaluateService;


/**
 * 服务评价管理Service业务层处理
 * 
 * @author gyz
 * @date 2024-09-11
 */
@Service
public class ServiceEvaluateServiceImpl implements IServiceEvaluateService 
{
    @Autowired
    private ServiceEvaluateMapper serviceEvaluateMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    /**
     * 查询服务评价管理
     * 
     * @param id 服务评价管理主键
     * @return 服务评价管理
     */
    @Override
    public ServiceEvaluate selectServiceEvaluateById(Long id)
    {
        return serviceEvaluateMapper.selectServiceEvaluateById(id);
    }

    /**
     * 查询服务评价管理列表
     * 
     * @param serviceEvaluate 服务评价管理
     * @return 服务评价管理
     */
    @Override
    public List<ServiceEvaluate> selectServiceEvaluateList(ServiceEvaluate serviceEvaluate)
    {
        return serviceEvaluateMapper.selectServiceEvaluateList(serviceEvaluate);
    }

    /**
     * 新增服务评价管理
     * 
     * @param serviceEvaluate 服务评价管理
     * @return 结果
     */
    @Override
    public int insertServiceEvaluate(ServiceEvaluate serviceEvaluate)
    {
        //新增评价
        int i = serviceEvaluateMapper.insertServiceEvaluate(serviceEvaluate);

        //新增后使用es计算商家评分
        // 基于Goods类 生成一个可以操作es数据的对象：目前还没有请求es
        IndexOperations indexOps = restTemplate.indexOps(ServiceEvaluate.class);

        // 判断goods对应的索引库是否存在：会请求es
        boolean exists = indexOps.exists();
        System.out.println("exists:" + exists);

        if (!exists) {
            //索引库不存在：创建索引库
            indexOps.create();
            //在内存中创建映射
            Document document = indexOps.createMapping();
            //将映射更新到es的索引库中
            indexOps.putMapping(document);
        }
        // 查询构建器
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        //构造聚合
        queryBuilder.addAggregation(AggregationBuilders.terms("shopAggs").field("m_id")
                .subAggregation(AggregationBuilders.avg("avgRate").field("rate")));
        //查询到的结果
        SearchHits<ServiceEvaluate> searchHits = restTemplate.search(queryBuilder.build(), ServiceEvaluate.class, IndexCoordinates.of("service_evaluate"));
        Aggregations aggregations = (Aggregations) searchHits.getAggregations().aggregations();
        ParsedLongTerms shopAggs = aggregations.get("shopAggs"); //获取第一层聚合的结果对象
        //获取聚合的店铺桶集合
        List<? extends Terms.Bucket> buckets = shopAggs.getBuckets();
        //遍历获取店铺桶的评分平均数
        buckets.forEach(bucket -> {
            ParsedAvg avgRate = (ParsedAvg) bucket.getAggregations().asMap().get("avgRate");
            System.out.println("Type:"+avgRate.getType());
            System.out.println("Value:"+avgRate.getValue());
            double rateValue = avgRate.getValue();
            //得到店铺id
            Long key = (Long) bucket.getKey();
            //如果新增的评价店铺id等于遍历中店铺桶的id,则修改商店评价
            if (key == serviceEvaluate.getMId()){
                //将得到的平均数插入店铺评分中(修改操作)
                Shop shop = new Shop();
                shop.setId(serviceEvaluate.getMId());
                shop.setRate((int) Math.round(rateValue));
                shopMapper.updateShop(shop);
            }
        });
        return i;
    }

    /**
     * 修改服务评价管理
     * 
     * @param serviceEvaluate 服务评价管理
     * @return 结果
     */
    @Override
    public int updateServiceEvaluate(ServiceEvaluate serviceEvaluate)
    {
        serviceEvaluate.setUpdateTime(DateUtils.getNowDate());
        return serviceEvaluateMapper.updateServiceEvaluate(serviceEvaluate);
    }

    /**
     * 批量删除服务评价管理
     * 
     * @param ids 需要删除的服务评价管理主键
     * @return 结果
     */
    @Override
    public int deleteServiceEvaluateByIds(Long[] ids)
    {
        return serviceEvaluateMapper.deleteServiceEvaluateByIds(ids);
    }

    /**
     * 删除服务评价管理信息
     * 
     * @param id 服务评价管理主键
     * @return 结果
     */
    @Override
    public int deleteServiceEvaluateById(Long id)
    {
        return serviceEvaluateMapper.deleteServiceEvaluateById(id);
    }
}
